﻿using QD.SQLHelper;
using QD.Tools;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QD.DbManager
{
    public partial class TableManager : DbBasic
    {
        EFDbContext dbContext;
        LogonConfig logonConfig;
        string curDbName;

        public TableManager(LogonConfig logonConfig, string curDbName)
        {
            InitializeComponent();

            this.curDbName = curDbName;
            this.logonConfig = logonConfig;
            string dbConnStr = logonConfig.GetConnectionStrings("master");

            EFDbContext masterContext = new EFDbContext(dbConnStr);
            IList<SysDatabases> databases = masterContext.Databases();
            foreach (SysDatabases db in databases)
            {
                this.comDbSource.Items.Add(db.name);
            }

            this.comDbSource.Text = curDbName;
            dbContext = new EFDbContext(logonConfig.GetConnectionStrings(curDbName));

            this.grid.RowTemplate.ContextMenuStrip = this.contextMenuStrip1;
            DataGridViewHelper.InitGrid(this.grid);

            this.treeView1.ContextMenuStrip = this.contextMenuStrip2;
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private void TableManager_Load(object sender, EventArgs e)
        {
        }

        void button1_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(Grid_DataBind));
            t.IsBackground = true;
            t.Start();
        }

        private void Grid_DataBind()
        {
            this.Invoke((EventHandler)(delegate
            {
                string tableName = this.txtTableName.Text.Trim();
                string condition = string.Empty;
                if (tableName.Length > 0)
                {
                    if (!QD.Tools.ValueTypeHelper.IsInt(tableName))
                    {
                        condition = string.Format("name like '%{0}%'", tableName);
                    }
                    else
                    {
                        condition = string.Format("object_id ={0}", tableName);
                    }
                }
                IList<SysTables> tables = dbContext.Tables(condition);
                this.grid.DataSource = tables;
            }));
        }

        private void txtTableName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.button1_Click(sender, e);
            }
        }

        private void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.grid.CopyFirstSelectedCellValue();
        }

        private void 创建新增脚本ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedCellCollection cells = this.grid.SelectedCells;
            if (cells.Count > 0)
            {
                DataGridViewCell cell = cells[0];
                StringBuilder sb = GetCreateTableSql(cell);

                Form frm = new SQLContainer(DbConfig.Instance.LogonConfig, DbConfig.Instance.DbConfigName, sb.ToString(), true);
                frm.ShowDialog();
            }
        }

        private void 创建选中行新增脚本ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedCellCollection cells = this.grid.SelectedCells;
            if (cells.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (DataGridViewCell cell in cells)
                {
                    sb.Append(GetCreateTableSql(cell));
                }

                Form frm = new SQLContainer(DbConfig.Instance.LogonConfig, DbConfig.Instance.DbConfigName, sb.ToString(), true);
                frm.ShowDialog();
            }
        }

        private StringBuilder GetCreateTableSql(DataGridViewCell cell)
        {
            int rowIndex = cell.RowIndex;
            DataGridViewRow dr = this.grid.Rows[rowIndex];
            string tableName = dr.Cells["name"].Value.ToString();

            StringBuilder sb = new StringBuilder();

            string sql1 = dbContext.GetTableCreateSql(tableName);
            sb.Append(sql1);

            string sql2 = dbContext.GetPrimaryIndex(tableName);
            if (sql2.Length > 0)
            {
                sb.Append(sql2);
            }

            string sql3 = dbContext.GetIndex(tableName);
            if (sql3.Length > 0)
            {
                sb.Append(sql3);
            }
            return sb;
        }

        private void button1_MouseEnter(object sender, EventArgs e)
        {
            ToolTip p = new ToolTip();
            p.ShowAlways = true;
            p.SetToolTip(this.button2, "请输入表名或完整标识后点击搜索");
        }

        private void 复制选中单元格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.grid.CopySelectedCellsValue();
        }

        private void 显示表结构ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedCellCollection cells = this.grid.SelectedCells;
            if (cells.Count > 0 && grid.Columns[cells[0].ColumnIndex].Name == "name")
            {
                string tableName = cells[0].Value.ToString();
                BindTreeView(dbContext, this.treeView1, tableName);
            }
        }

        private void grid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                string tableName = this.grid.Rows[e.RowIndex].Cells["name"].Value.ToString();
                BindTreeView(dbContext, this.treeView1, tableName);
            }
        }

        //绑定表结构
        public static void BindTreeView(EFDbContext dbContext, TreeView tree, string tableName)
        {
            tree.Nodes.Clear();
            TreeNode rootNode = new TreeNode("对象(" + tableName + ")");
            //rootNode.NodeFont = new Font(this.treeView1.Font, FontStyle.Bold);

            tree.Nodes.Add(rootNode);

            //绑定表的列信息
            IList<SysColumns> columns = dbContext.GetObjColumns(tableName);
            TreeNode columnNode = new TreeNode("列信息(" + columns.Count + ")");
            rootNode.Nodes.Add(columnNode);
            foreach (SysColumns col in columns)
            {

                TreeNode node = new TreeNode();
                string type = "";
                if (col.precision == 0)
                {
                    type = "(" + (col.max_length == -1 ? "max" : col.max_length.ToString()) + ")";
                }
                else
                {
                    type = "(" + col.precision + "," + col.scale + ")";
                }
                if (col.is_nullable)
                {
                    type += (" " + "null");
                }

                if (col.is_identity)
                {
                    type += (" " + "自增量");
                    node.ForeColor = Color.Green;
                }

                if (col.is_computed)
                {
                    type += (" " + "计算列");
                }
                node.Text = col.name + "  " + col.typename + type;
                columnNode.Nodes.Add(node);
            }
            rootNode.Expand();
            columnNode.Expand();


            TreeNode rootNode2 = new TreeNode("索引信息");
            tree.Nodes.Add(rootNode2);

            //绑定表的主键
            IList<SysIndex> pkIndexs = dbContext.GetIndexs(tableName, true);
            if (pkIndexs.Count > 0)
            {
                string pkCols = "";
                foreach (SysIndex pk in pkIndexs)
                {
                    pkCols += ("," + pk.IndexColumnName);
                }
                TreeNode rootNodePK = new TreeNode("主键索引 " + pkIndexs[0].IndexName + " ((" + pkCols.Substring(1) + ") " + pkIndexs[0].Type_Desc + ")");
                rootNodePK.ForeColor = Color.Blue;
                rootNode2.Nodes.Add(rootNodePK);
            }

            //绑定表的非主键索引
            IList<SysIndex> ixIndexs = dbContext.GetIndexs(tableName, false);
            if (ixIndexs.Count > 0)
            {
                IList<string> ixNames = ixIndexs.Select(p => p.IndexName).Distinct().ToList();
                foreach (string ix in ixNames)
                {
                    IList<SysIndex> c_ixIndexs = ixIndexs.Where(p => p.IndexName == ix).ToList();
                    string c_ixCols = "";
                    foreach (SysIndex cix in c_ixIndexs)
                    {
                        c_ixCols += ("," + cix.IndexColumnName);
                    }
                    TreeNode rootNodeIX = new TreeNode("非主键索引 " + c_ixIndexs[0].IndexName + " ((" + c_ixCols.Substring(1) + ") " + c_ixIndexs[0].Type_Desc + ")");
                    rootNode2.Nodes.Add(rootNodeIX);
                }
            }
            rootNode2.ExpandAll();
        }

        private void 复制ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            TreeViewHelper.CopyFirstSelectedNodeText(this.treeView1);
        }

        private void comDbSource_SelectedIndexChanged(object sender, EventArgs e)
        {
            dbContext = new EFDbContext(logonConfig.GetConnectionStrings(this.comDbSource.Text));
        }

        private void 查看数据前100行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedCellCollection cells = this.grid.SelectedCells;
            if (cells.Count > 0)
            {
                DataGridViewCell cell = cells[0];

                int rowIndex = cell.RowIndex;
                DataGridViewRow dr = this.grid.Rows[rowIndex];
                string tableName = dr.Cells["name"].Value.ToString();

                string sql = "select top 100 * from " + tableName;
                Form frm = new SQLContainer(DbConfig.Instance.LogonConfig, this.comDbSource.SelectedItem.ToString(), sql, true);
                frm.ShowDialog();
            }
        }

        private void 导出数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedCellCollection cells = this.grid.SelectedCells;
            if (cells.Count > 0)
            {
                DataGridViewCell cell = cells[0];

                int rowIndex = cell.RowIndex;
                DataGridViewRow dr = this.grid.Rows[rowIndex];
                string tableName = dr.Cells["name"].Value.ToString();

                string sql = "select * from " + tableName;

                dbContext = new EFDbContext(logonConfig.GetConnectionStrings(curDbName));
                DataTable dt = dbContext.Query(sql);
                dt.TableName = tableName;
                SaveFileMag frm = new SaveFileMag(dt);
                frm.ShowDialog();
            }
        }
    }
}
